package com.association.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Description: 类作用描述
 * @Author: xq
 * @CreateDate: 2018/12/28 17:12
 * @Version: 1.0
 */
@Component
public class MessagesManager implements ApplicationContextAware {

    public static final Logger logger = LoggerFactory.getLogger(MessagesManager.class);

    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    private MessagesManager(){
    }

    public static String getMessage(Integer key){
        String msg = "";
        try {
            //msg = messages.getProperty(String.valueOf(key));
            msg = applicationContext.getEnvironment().getProperty(String.valueOf(key));
//            msg = encoding(msg);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("MessagesManager getMessage 异常："+e);
        }
        return msg ;
    }
    public static String getMessage(Integer key,String... msg){
        String msgConfig = applicationContext.getEnvironment().getProperty(String.valueOf(key));
//        msgConfig = encoding(msgConfig);
        if(msgConfig == null || "".equals(msgConfig)){
            if(msg != null){
                return StringUtils.join(msg);
            }else{
                return "" ;
            }
        }else{
            for(int i = 0;i < msg.length;i++){
                msgConfig = msgConfig.replaceFirst("%s",String.valueOf(msg[i]));
            }
            return msgConfig;
        }
    }

    private static String encoding(String msg){
        try {
            if(msg == null ){
                return "" ;
            }
            msg =new String(msg.getBytes("ISO-8859-1"), "UTF-8");
        } catch (Exception e) {
            logger.error("msg:"+msg+"转码异常",e);
            return  ""  ;
        }
        return msg ;
    }
}
